//
//  AddressView.m
//  560315
//
//  Created by ZERO on 16/1/16.
//  Copyright © 2016年 jishubu0315. All rights reserved.//

#define kRedBackgroundColor [UIColor colorWithRed:38/255.0 green:145/255.0 blue:209/255.0 alpha:1]
#define IPHONE_HEIGHT UIScreen.mainScreen.bounds.size.height
#import "AddressView.h"

@interface AddressView ()<UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic, strong) NSMutableArray *provinces;
@property (nonatomic, strong) NSMutableArray *cityArray;    // 城市数据
@property (nonatomic, strong) NSMutableArray *areaArray;    // 区信息 13472906715
@property (nonatomic, strong) NSMutableArray *selectedArray;

@property (nonatomic, strong) NSNumber *ProId;
@property (nonatomic, strong) NSNumber *CityId;
@property (nonatomic, strong) NSNumber *AreaId;

@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) UIView       *lineView;
/** 全部省*/
@property (nonatomic, strong) NSArray *allPro;
/** 全部市*/
@property (nonatomic, strong) NSArray *allCity;
/** 全部区*/
@property (nonatomic, strong) NSArray *allArea;

//@property (nonatomic, strong, readonly) UIWindow *bgWindow;

@end

@implementation AddressView
//@synthesize bgWindow;

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)initWith:(AddressListType)type{
    self = [super init];
    if (self) {
        
        self.shadowView = [UIView new];
        self.shadowView.frame = [UIScreen mainScreen].bounds;
        self.shadowView.backgroundColor = [UIColor blackColor];
        self.shadowView.alpha = 0;
        self.shadowView.userInteractionEnabled = YES;
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissPicker)];
        [self.shadowView addGestureRecognizer:tap];
        
        self.backgroundColor = [UIColor whiteColor];
        self.bounds = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 195);
        self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 35, self.bounds.size.width, self.bounds.size.height - 35)];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        _pickerView.backgroundColor = [UIColor whiteColor];
  
        
        self.lineView = [UIView new];
        self.lineView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 35);
        _lineView.backgroundColor = [UIColor whiteColor];
        
        UIView *bottoml = [UIView new];
        bottoml.frame = CGRectMake(0, 34, [UIScreen mainScreen].bounds.size.width, 1);
        bottoml.backgroundColor = [UIColor colorWithRed:231/255.0 green:232/255.0 blue:234/255.0 alpha:1];
        [self.lineView addSubview:bottoml];

        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.frame = CGRectMake(self.lineView.frame.size.width - 45, 0, 43, 35);
        btn.tintColor = kRedBackgroundColor;
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        [btn setTitle:@"完成" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
        [self.lineView addSubview:btn];
        
  
//        self.icon = [[UIImageView alloc] initWithFrame:CGRectMake(48, 12, 12, 12)];
//        _icon.image = [UIImage imageNamed:@"quehuanq_image"];
//        _icon.hidden = YES;
//        [self.lineView addSubview:_icon];

        
        self.leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.leftBtn.frame = CGRectMake(8, 10, 76, 15);
        self.leftBtn.backgroundColor = [UIColor clearColor];

//        [self.leftBtn setTitle:@"国外" forState:UIControlStateNormal];
        [self.leftBtn setImage:[UIImage imageNamed:@"nei_image"] forState:UIControlStateNormal];
        self.leftBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        [self.leftBtn setTitleColor:[UIColor colorWithRed:57 / 255.0 green:146 / 255.0 blue:209 / 255.0 alpha:1] forState:UIControlStateNormal];
        self.leftBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.leftBtn addTarget:self action:@selector(leftClick) forControlEvents:UIControlEventTouchUpInside];
        self.leftBtn.hidden = YES;
        [self.lineView addSubview:self.leftBtn];
        [self addSubview:self.lineView];
        
        self.type = type;

        NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"AddressView.bundle" ofType:nil];
        NSBundle *AddressBundle = [[NSBundle alloc]initWithPath:bundlePath];
        
        NSString *path1 = [AddressBundle pathForResource:@"province" ofType:@"plist"];
        self.allPro = [[NSArray alloc] initWithContentsOfFile:path1];
        [_allPro enumerateObjectsUsingBlock:^(NSDictionary  *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.provinces addObject:obj];
        }];
        
        NSString *path2 = [AddressBundle pathForResource:@"city" ofType:@"plist"];
        self.allCity = [[NSArray alloc] initWithContentsOfFile:path2];
        [_allCity enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj[@"i_province_id"] isEqualToString:[_allPro firstObject][@"id"] ]) {
                [self.cityArray addObject:obj];
            }
        }];
        
        if (type == AddressListThreeLine) {
            NSString *path3 = [AddressBundle pathForResource:@"county" ofType:@"plist"];
            self.allArea = [[NSArray alloc] initWithContentsOfFile:path3];
            [_allArea enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj[@"i_city_id"] isEqualToString:[_allCity firstObject][@"nvc_code"] ]) {
                    [self.areaArray addObject:obj];
                }
            }];
        }
        

        [self addSubview:_pickerView];
        
        UIView *view = [UIView new];
        view.userInteractionEnabled = YES;
        view.frame = CGRectMake(0, 65, [UIScreen mainScreen].bounds.size.width, 30);
        view.backgroundColor = [UIColor lightGrayColor];
        view.alpha = 0.2;
        [_pickerView addSubview:view];

        self.province = @"不限";
        self.city = @"";
        self.area = @"";
    }
    return self;
}
- (void)leftClick{
    [self.delegate leftAction];
    [self dismissPicker];
}
- (void)click{

    for (NSMutableDictionary *dic in _allPro) {
        if ([self.province containsString:[dic objectForKey:@"province"]]) {
            self.provinceStr = [dic objectForKey:@"province"];
            break;
        }else{
            self.provinceStr = @"";
        }
    }
    
    for (NSMutableDictionary *dic in _allCity) {
        if ([self.city containsString:[dic objectForKey:@"nvc_name"]]) {
            self.cityStr = [dic objectForKey:@"nvc_name"];
            break;
        }else{
            self.cityStr = @"";
        }
        
    }
    
    if (self.type == AddressListThreeLine) {
        
        if ([self.city isEqualToString:@"北京市"]||[self.city isEqualToString:@"天津市"]||[self.city isEqualToString:@"上海市"]||[self.city isEqualToString:@"重庆市"]) {
            for (NSMutableDictionary *dic in _allCity) {
                if ([self.area containsString:[dic objectForKey:@"nvc_name"]]) {
                    self.areaStr = [dic objectForKey:@"nvc_name"];
                    break;
                }else{
                    self.areaStr = @"";
                }
            }
    
        }else{
            for (NSMutableDictionary *dic in _allArea) {
                if ([self.area containsString:[dic objectForKey:@"nvc_name"]]) {
                    self.areaStr = [dic objectForKey:@"nvc_name"];
                    break;
                }else{
                    self.areaStr = @"";
                }
                
            }
    
        }

    }
    
    
    [self cancelPicker];


}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    if (self.type == AddressListThreeLine) {
        return 3;
    }
    return 2;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return self.provinces.count;
    }else if(component == 1) {
        return self.cityArray.count;
    }else{
        return self.areaArray.count;
    }
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    

    if (component == 0) {
        [self.cityArray removeAllObjects];
        // 市添加不限
        if (row != 0) {
            [self.cityArray addObject:[_allCity firstObject]];
        }
        [_allCity enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj[@"i_province_id"] isEqualToString:_allPro[row][@"id"] ]) {
                [self.cityArray addObject:obj];
            }
        }];
        
        if (self.type == AddressListThreeLine) {
            [self.areaArray removeAllObjects];
            for (NSDictionary *dic in _allArea) {
                if ([dic[@"i_city_id"] isEqualToString:[self.cityArray firstObject][@"nvc_code"] ]) {
                    [self.areaArray addObject:dic];
                }
            }
        }

        [pickerView reloadComponent:1];
        if (self.type == AddressListThreeLine) {
            [pickerView reloadComponent:2];
        }
        [pickerView selectRow:0 inComponent:1 animated:YES];
        if (self.type == AddressListThreeLine) {
            [pickerView selectRow:0 inComponent:2 animated:YES];
        }
    }else if (component == 1) {
        if (self.type == AddressListThreeLine) {
            [self.areaArray removeAllObjects];
            // 区添加不限
            if (row != 0) {
                [self.areaArray addObject:[_allArea firstObject]];
            }
    
            [_allArea enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj[@"i_city_id"] isEqualToString:self.cityArray[row][@"nvc_code"] ]) {
                    [self.areaArray addObject:obj];
                }
            }];
            [pickerView reloadComponent:2];
            [pickerView selectRow:0 inComponent:2 animated:YES];
        }
    }else{
        
    }
    
    NSInteger index = [_pickerView selectedRowInComponent:0];
    NSInteger index1 = [_pickerView selectedRowInComponent:1];

    self.province = self.provinces[index][@"province"];
    self.ProId = self.provinces[index][@"id"];
    
    self.city = self.cityArray[index1][@"nvc_name"];
    self.CityId = self.cityArray[index1][@"nvc_code"];
    
    if (self.type == AddressListThreeLine) {
        NSInteger index2 = [_pickerView selectedRowInComponent:2];
        
        if (self.areaArray.count != 0) {
            self.area = self.areaArray[index2][@"nvc_name"];
            self.AreaId = self.areaArray[index2][@"nvc_code"];
        }else{
            self.area = @"";
//            self.AreaId = @0;
        }
    }
    

}


- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        return self.provinces[row][@"province"];
    }else if(component == 1){
        return self.cityArray[row][@"nvc_name"];
    }else{
        if (self.areaArray.count != 0) {
            return self.areaArray[row][@"nvc_name"];
        }else{
            return nil;
        }
    }
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    // 去掉两条线
    ((UIView *)[pickerView.subviews objectAtIndex:2]).backgroundColor
    = [UIColor clearColor];
    ((UIView *)[pickerView.subviews objectAtIndex:3]).backgroundColor
    = [UIColor clearColor];
    
    UILabel *lbl = [UILabel new];
    lbl.textAlignment = 1;
    if (component == 0) {
        lbl.text = [_provinces objectAtIndex:row][@"province"];
    }else if(component == 1){
        lbl.text = [_cityArray objectAtIndex:row][@"nvc_name"];
    }else{
        lbl.text = [_areaArray objectAtIndex:row][@"nvc_name"];
    }
    
    return lbl;
}
- (void)showInView
{
    self.frame = CGRectMake(0, self.shadowView.frame.size.height, self.frame.size.width, self.frame.size.height);
    
    
    [UIView animateWithDuration:0.3 animations:^{
        self.frame = CGRectMake(0, self.shadowView.frame.size.height - self.frame.size.height, self.frame.size.width, self.frame.size.height);
        self.shadowView.alpha = 0.2;
    }];
    [[[[UIApplication sharedApplication] windows] firstObject] addSubview:self.shadowView];
    [[[[UIApplication sharedApplication] windows] firstObject] addSubview:self];
    
}
- (void) dismissPicker{
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.frame = CGRectMake(0, IPHONE_HEIGHT, self.frame.size.width, self.frame.size.height);
                         self.shadowView.alpha = 0;
                         
                     }
                     completion:^(BOOL finished){
                         [self removeFromSuperview];
                         [self.shadowView removeFromSuperview];
                     }];

}
- (void)cancelPicker
{
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.frame = CGRectMake(0, IPHONE_HEIGHT, self.frame.size.width, self.frame.size.height);
                         self.shadowView.alpha = 0;

                     }
                     completion:^(BOOL finished){
                         [self removeFromSuperview];
                         // 处理直辖市
//                         if ([self.city isEqualToString:@"北京市"]||[self.city isEqualToString:@"天津市"]||[self.city isEqualToString:@"上海市"]||[self.city isEqualToString:@"重庆市"]) {
//                             self.city = @"";
//                             self.cityStr = self.areaStr;
//                             self.areaStr = @"";
//                         }
                         if ([self.province isEqualToString:@"不限" ]) {
                             self.province = @"";
                             self.provinceStr = @"";
                             self.ProId = nil;
                         }
                         if ([self.city isEqualToString:@"不限" ]) {
                             self.city = @"";
                             self.cityStr = @"";
                             self.CityId = nil;
                         }
                         if ([self.area isEqualToString:@"不限" ]) {
                             self.area = @"";
                             self.areaStr = @"";
                             self.AreaId = nil;
                         }
                         [self.delegate complete:self Str:[NSString stringWithFormat:@"%@%@%@",self.province,self.city,self.area]];
                         [self.delegate reback:self Pro:self.provinceStr City:self.cityStr Area:self.areaStr];
                         [self.delegate SelectId:self Pro:self.ProId City:self.CityId Area:self.AreaId];
                         NSLog(@"省:%@   市:%@   县:%@",self.provinceStr,self.cityStr, self.areaStr);
                         [self.shadowView removeFromSuperview];
                     }];
    
}

- (NSMutableArray *)provinces{
    if (!_provinces) {
        self.provinces = [@[] mutableCopy];
    }
    return _provinces;
}

- (NSMutableArray *)cityArray{
    if (!_cityArray) {
        self.cityArray = [@[] mutableCopy];
    }
    return _cityArray;
}
- (NSMutableArray *)areaArray{
    if (!_areaArray) {
        self.areaArray = [@[] mutableCopy];
    }
    return _areaArray;
}
- (NSMutableArray *)selectedArray{
    if (!_selectedArray) {
        self.selectedArray = [@[] mutableCopy];
    }
    return _selectedArray;
}
-(NSNumber *)ProId{
    if (!_ProId) {
        _ProId = @0;
    }
    return _ProId;
}

-(NSNumber *)CityId{
    if (!_CityId) {
        _CityId = @0;
    }
    return _CityId;
}

-(NSNumber *)AreaId{
    if (!_AreaId) {
        _AreaId = @0;
    }
    return _AreaId;
}

@end
